import sys
import asyncio
import json
from jsonpath import jsonpath
import websockets
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTextEdit
from PyQt5.QtGui import QFont
from PyQt5.QtCore import QThread, pyqtSignal

class AsyncWorker(QThread):
    text_updated = pyqtSignal(str)

    def __init__(self, parent=None):
        super().__init__(parent)

    def run(self):
        # 在这里运行异步代码
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        
        try:
            loop.run_until_complete(self.async_task())
        finally:
            loop.close()

    async def async_task(self):
        await self.websocket_task()

    async def websocket_task(self):
        global close
        close = True
        async with websockets.connect("ws://172.168.10.92:8888/216006982824?use=2", ping_interval=None) as ws:
            await ws.send("token")
            while close:
                result = await ws.recv()
                json_data = json.loads(result)
                self.check_json(json_data)
            await ws.close()

    def check_json(self, json_data):
        Token = json_data.get("Type")  # 标签类型
        if Token == 1:  # 1用户发言
            self.msg(json_data)
        elif Token == 2:  # 2用户点赞
            self.praise(json_data)
        elif Token == 3:  # 3用户入房
            self.welcome(json_data)
        elif Token == 4:  # 感谢关注
            self.text_updated.emit(str(json_data))
        elif Token == 5:  # 5用户礼物
            self.thank(json_data)
        elif Token == 6:  # 6人数统计
            self.check(json_data)
        else:
            self.text_updated.emit(str(json_data))

    def msg(self, data):
        load_json_data = json.loads(data.get("Data"))
        用户名 = jsonpath(load_json_data, '$.User.Nickname')
        用户等级 = jsonpath(load_json_data, '$.User.PayLevel')
        粉丝团 = jsonpath(load_json_data, '$.User.FansClub.ClubName')
        用户发言 = jsonpath(load_json_data, '$.Content')
        if 用户发言[0] == "#关闭":
            global close
            close = False
        # else:
            #self.text_updated.emit(f"用户名: {用户名[0]}, 用户等级: {用户等级[0]}")

    def praise(self, data):
        load_json_data = json.loads(data.get("Data"))
        用户点赞 = jsonpath(load_json_data, '$.Content')
        self.text_updated.emit(f"感谢{用户点赞[0]}")

    def welcome(self, data):
        load_json_data = json.loads(data.get("Data"))
        用户名 = jsonpath(load_json_data, '$.User.Nickname')
        粉丝团 = jsonpath(load_json_data, '$.User.FansClub.ClubName')
        if 粉丝团[0] == "Reset":
            self.text_updated.emit(f"欢迎粉丝: {用户名[0]}")
        else:
            self.text_updated.emit(f"欢迎: {用户名[0]}")

    def thank(self, data):
        load_json_data = json.loads(data.get("Data"))
        粉丝团 = jsonpath(load_json_data, '$.User.FansClub.ClubName')
        用户送礼 = jsonpath(load_json_data, '$.Content')
        if 粉丝团[0] == "Reset":
            self.text_updated.emit(f"感谢老板: {用户送礼[0]}")
        else:
            self.text_updated.emit(f"感谢: {用户送礼[0]}")

    def check(self, data):
        load_json_data = json.loads(data.get("Data"))
        房间统计 = jsonpath(load_json_data, '$.Content')
        self.text_updated.emit(f"房间统计: {房间统计[0]}")

class TextDisplayApp(QWidget):
    def __init__(self):
        super().__init__()
        
        self.initUI()
        self.start_async_worker()

    def initUI(self):
        self.setWindowTitle('互动区')
        # 设置窗体大小和圆角
        self.setFixedSize(400, 300)
        self.setStyleSheet("QWidget { border-radius: 10px; background-color: #87CEEB; }")
 
        layout = QVBoxLayout()
        
        # 初始化文本编辑框，并设置只读和字体样式
        self.text_edit = QTextEdit(self)
        self.text_edit.setReadOnly(True)
        self.text_edit.setFont(QFont('Arial', 12))
        self.text_edit.setStyleSheet("""
            QTextEdit {
                background-color: #ADD8E6;
                border: 1px solid #cccccc;
                border-radius: 5px;
                padding: 10px;
                color: #333333;
                font-family: 'Arial', sans-serif;
                font-size: 14px;
            }
        """)
        layout.addWidget(self.text_edit)
        
        # 设置布局并应用样式
        self.setLayout(layout)
        self.setStyleSheet(self.styleSheet() + """
            QWidget {
                font-family: 'Arial', sans-serif;
                font-size: 12px;
                color: #87CEEB;
                border: 2px solid #87CEEB;
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            }
        """)
        # layout = QVBoxLayout()
        
        # self.text_edit = QTextEdit(self)
        # self.text_edit.setReadOnly(True)
        # layout.addWidget(self.text_edit)
        
        # self.setLayout(layout)
        # self.resize(400, 300)

    def start_async_worker(self):
        self.worker = AsyncWorker()
        self.worker.text_updated.connect(self.update_text)
        self.worker.start()

    def update_text(self, text):
        self.text_edit.append(text)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = TextDisplayApp()
    ex.show()
    sys.exit(app.exec_())